<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>【初阶数据结构】星河中的光影 “排” 象：排序（下） | 澪贰</title><meta name="author" content="澪贰"><meta name="copyright" content="澪贰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="接上一篇，解决掉剩余的排序方法，本篇有些许难度，建议巩固好上一篇再来进行本篇的学习">
<meta property="og:type" content="article">
<meta property="og:title" content="【初阶数据结构】星河中的光影 “排” 象：排序（下）">
<meta property="og:url" content="http://example.com/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8B%EF%BC%89/index.html">
<meta property="og:site_name" content="澪贰">
<meta property="og:description" content="接上一篇，解决掉剩余的排序方法，本篇有些许难度，建议巩固好上一篇再来进行本篇的学习">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250225211552.png">
<meta property="article:published_time" content="2025-02-25T13:28:54.000Z">
<meta property="article:modified_time" content="2025-02-25T13:28:54.000Z">
<meta property="article:author" content="澪贰">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="数据结构">
<meta property="article:tag" content="排序算法">
<meta property="article:tag" content="快速排序">
<meta property="article:tag" content="归并排序">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250225211552.png"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "【初阶数据结构】星河中的光影 “排” 象：排序（下）",
  "url": "http://example.com/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8B%EF%BC%89/",
  "image": "https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250225211552.png",
  "datePublished": "2025-02-25T13:28:54.000Z",
  "dateModified": "2025-02-25T13:28:54.000Z",
  "author": [
    {
      "@type": "Person",
      "name": "澪贰",
      "url": "http://example.com/"
    }
  ]
}</script><link rel="shortcut icon" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/cat_icon.ico"><link rel="canonical" href="http://example.com/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8B%EF%BC%89/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!true && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          const hour = new Date().getHours()
          const isNight = hour <= 6 || hour >= 18
          if (theme === undefined) isNight ? activateDarkMode() : activateLightMode()
          else theme === 'light' ? activateLightMode() : activateDarkMode()
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":150,"languages":{"author":"作者: 澪贰","link":"链接: ","source":"来源: 澪贰","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'medium_zoom',
  Snackbar: {"chs_to_cht":"已切换为繁体中文","cht_to_chs":"已切换为简体中文","day_to_night":"已切换为深色模式","night_to_day":"已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【初阶数据结构】星河中的光影 “排” 象：排序（下）',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/water02.jpg);"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250225211552.png);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">澪贰</span></a><a class="nav-page-title" href="/"><span class="site-name">【初阶数据结构】星河中的光影 “排” 象：排序（下）</span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">【初阶数据结构】星河中的光影 “排” 象：排序（下）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-02-25T13:28:54.000Z" title="发表于 2025-02-25 21:28:54">2025-02-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-02-25T13:28:54.000Z" title="更新于 2025-02-25 21:28:54">2025-02-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">初阶数据结构</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">总字数:</span><span class="word-count">4387</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><div id="post-outdate-notice" data="{&quot;limitDay&quot;:365,&quot;messagePrev&quot;:&quot;It has been&quot;,&quot;messageNext&quot;:&quot;days since the last update, the content of the article may be outdated.&quot;,&quot;postUpdate&quot;:&quot;2025-02-25 21:28:54&quot;}" hidden></div><p>接上一篇，解决掉剩余的排序方法，本篇有些许难度，建议巩固好上一篇再来进行本篇的学习</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/145803285">【初阶数据结构】星河中的光影 “排” 象：排序（上）</a></p>
</blockquote>
<h1 id="交换排序"><a href="#交换排序" class="headerlink" title="交换排序"></a>交换排序</h1><h2 id="冒泡排序（BubbleSort）"><a href="#冒泡排序（BubbleSort）" class="headerlink" title="冒泡排序（BubbleSort）"></a>冒泡排序（BubbleSort）</h2><p><strong>基本思想：</strong> 所谓交换，就是根据序列中两个记录键值的比较结果来对换这两个记录在序列中的位置，交换排序的特点是：将<code>键值较大</code>的记录向序列的<code>尾部移动</code>，<code>键值较小</code>的记录向序列的<code>前部移动</code></p>
<p><code>冒泡排序</code>在C语言部分进行过详细的解析，这里就不过多赘述</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/143477683">关于我、重生到500年前凭借C语言改变世界科技vlog.14——常见C语言算法</a></p>
</blockquote>
<h2 id="快速排序（QuickSort）"><a href="#快速排序（QuickSort）" class="headerlink" title="快速排序（QuickSort）"></a>快速排序（QuickSort）</h2><p><code>快速排序</code>是 Hoare 于 1962 年提出的一种二叉树结构的交换排序方法，<strong>其基本思想为：</strong> 任取待排序元素序列中的<code>某元素作为基准值</code>，按照该排序码将待排序集合分割成<code>两子序列</code>，<code>左子序列</code>中所有元素均<code>小于基准值</code>，<code>右子序列</code>中所有元素均<code>大于基准值</code>，然后最左右子序列重复该过程，直到所有元素都排列在相应位置上为止</p>
<h3 id="hoare版本"><a href="#hoare版本" class="headerlink" title="hoare版本"></a>hoare版本</h3><p><strong>动图理解：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/8eec32b2f9014c03b7d7d67782af37c9.gif" alt="请添加图片描述"></p>
<p>💻<strong>排序实现：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">QuickSort1</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (left &gt;= right)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	<span class="type">int</span> begin = left, end = right;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//随机选key</span></span><br><span class="line">	<span class="type">int</span> randi = left + (<span class="built_in">rand</span>() % (right - left + <span class="number">1</span>));</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[left], &amp;a[randi]);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//三数取中</span></span><br><span class="line">	<span class="comment">//int midi = GetMidNumi(a, left, right);</span></span><br><span class="line">	<span class="comment">//Swap(&amp;a[midi], &amp;a[left]);</span></span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> keyi = left;</span><br><span class="line">	<span class="keyword">while</span> (left &lt; right)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//右边找小</span></span><br><span class="line">		<span class="keyword">while</span> (left &lt; right &amp;&amp; a[right] &gt;= a[keyi])</span><br><span class="line">			--right;</span><br><span class="line"></span><br><span class="line">		<span class="comment">//左边找大</span></span><br><span class="line">		<span class="keyword">while</span> (left &lt; right &amp;&amp; a[left] &lt;= a[keyi])</span><br><span class="line">			++left;</span><br><span class="line"></span><br><span class="line">		<span class="built_in">Swap</span>(&amp;a[left], &amp;a[right]);</span><br><span class="line">	&#125;</span><br><span class="line">		<span class="built_in">Swap</span>(&amp;a[keyi], &amp;a[left]);</span><br><span class="line">		keyi = left;</span><br><span class="line"></span><br><span class="line">		<span class="built_in">QuickSort1</span>(a, begin, keyi - <span class="number">1</span>);</span><br><span class="line">		<span class="built_in">QuickSort1</span>(a, keyi + <span class="number">1</span>, end);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>代码解读：</strong> </p>
<ol>
<li><code>if (left &gt;= right)</code>， 如果左边界大于等于右边界，说明子数组已经有序或为空，直接返回</li>
<li>随机选 <code>key</code></li>
<li>当左边界小于右边界时，继续分区操作。<code>右边找小</code>，从右向左找到第一个小于基准元素的元素；<code>左边找大</code>，从左向右找到第一个大于基准元素的元素。交换左右找到的元素</li>
<li>最后将基准元素放到正确的位置，更新基准元素的索引</li>
<li>此时基准元素所放置的位置就是正确的排序位置，基准元素左右两边任然无序，所以对左右两边进行循环操作，<code>每循环一次就确定一个数的位置</code></li>
</ol>
<p>🔥<strong>值得注意的是：</strong><br>选取 <code>key</code> 的方式有三种</p>
<ol>
<li>选第一个数为 <code>key</code></li>
<li>三数取中值</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">GetMidNumi</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span> mid = (left + right) / <span class="number">2</span>;</span><br><span class="line">	<span class="keyword">if</span> (a[left] &lt; a[mid])</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (a[left] &gt; a[right])</span><br><span class="line">			<span class="keyword">return</span> left;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (a[mid] &lt; a[right])</span><br><span class="line">			<span class="keyword">return</span> mid;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">			<span class="keyword">return</span> right;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="comment">//a[left] &gt; a[mid]</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (a[mid] &gt; a[right])</span><br><span class="line">			<span class="keyword">return</span> mid;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (a[right] &gt; a[left])</span><br><span class="line">			<span class="keyword">return</span> left;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">			<span class="keyword">return</span> right;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>随机选 <code>key</code>，经过算法研究发现该选 <code>key</code> 方式是最有效的</li>
</ol>
<h3 id="挖坑法"><a href="#挖坑法" class="headerlink" title="挖坑法"></a>挖坑法</h3><p><strong>动图理解：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/d32dfc810a9246ccbe69b6971458008c.gif" alt="请添加图片描述"></p>
<p>💻<strong>排序实现：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">QuickSort2</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (left &gt;= right)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	<span class="type">int</span> begin = left, end = right;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//随机选key</span></span><br><span class="line">	<span class="type">int</span> randi = left + (<span class="built_in">rand</span>() % (right - left + <span class="number">1</span>));</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[left], &amp;a[randi]);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//三数取中</span></span><br><span class="line">	<span class="comment">//int midi = GetMidNumi(a, left, right);</span></span><br><span class="line">	<span class="comment">//Swap(&amp;a[midi], &amp;a[left]);</span></span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> key = a[left];</span><br><span class="line">	<span class="type">int</span> hole = left;</span><br><span class="line">	<span class="keyword">while</span> (left &lt; right)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//右边找小</span></span><br><span class="line">		<span class="keyword">while</span> (left &lt; right &amp;&amp; a[right] &gt;= key)</span><br><span class="line">			--right;</span><br><span class="line"></span><br><span class="line">		a[hole] = a[right];</span><br><span class="line">		hole = right;</span><br><span class="line"></span><br><span class="line">		<span class="comment">//左边找大</span></span><br><span class="line">		<span class="keyword">while</span> (left &lt; right &amp;&amp; a[left] &lt;= key)</span><br><span class="line">			++left;</span><br><span class="line"></span><br><span class="line">		a[hole] = a[left];</span><br><span class="line">		hole = left;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	a[hole] = key;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">QuickSort2</span>(a, begin, hole - <span class="number">1</span>);</span><br><span class="line">	<span class="built_in">QuickSort2</span>(a, hole + <span class="number">1</span>, end);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>代码解读：</strong> </p>
<ol>
<li>选择左边界元素作为基准元素 <code>key</code>，并将其位置标记为 <code>hole</code>（坑）</li>
<li>从右向左扫描，找到第一个小于 <code>key</code> 的元素，将其填入 <code>hole</code> 位置，并更新 <code>hole</code> 为该元素的位置。</li>
<li>从左向右扫描，找到第一个大于 <code>key</code> 的元素，将其填入 <code>hole</code> 位置，并更新 <code>hole</code> 为该元素的位置。</li>
<li>不断重复上述两个步骤，直到 <code>left</code> 和 <code>right</code> 相遇。</li>
<li>最后将基准元素 <code>key</code> 填入最终的 <code>hole</code> 位置</li>
</ol>
<p>🔥<strong>值得注意的是：</strong> 在从右向左查找小于 <code>key</code> 的元素时，<code>right</code> 指针会不断向左移动。如果不添加 <code>left &lt; right</code> 这个条件，<code>right</code> 指针可能会一直向左移动，越过 <code>left</code> 指针，导致访问到数组范围之外的元素，从而引发越界错误。例如，当数组中的元素都大于等于 <code>key</code> 时，如果没有 <code>left &lt; right</code> 的限制，<code>right</code> 指针会一直向左移动，最终可能访问到数组的负索引位置，这是不合法的。<code>从左向右查找大于 key 的元素也是同理</code></p>
<h3 id="前后指针法"><a href="#前后指针法" class="headerlink" title="前后指针法"></a>前后指针法</h3><p><strong>动图理解：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/f8353d18aec14fa68c126520255bf6f2.gif" alt="请添加图片描述"></p>
<p>💻<strong>排序实现：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">QuickSort3</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (left &gt;= right)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> randi = left + (<span class="built_in">rand</span>() % (right - left + <span class="number">1</span>));</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[left], &amp;a[randi]);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//定义基准值以及cur和dest</span></span><br><span class="line">	<span class="type">int</span> keyi = left;</span><br><span class="line">	<span class="type">int</span> dest = left, cur = left + <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (cur &lt;= right)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (a[cur] &lt; a[keyi] &amp;&amp; ++dest != cur)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">Swap</span>(&amp;a[cur], &amp;a[dest]);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//无论cur位置的值是否小于基准值，cur都要++，所以留到这里做调整</span></span><br><span class="line">		cur++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[keyi], &amp;a[dest]);</span><br><span class="line">	<span class="built_in">QuickSort3</span>(a, left, dest - <span class="number">1</span>);</span><br><span class="line">	<span class="built_in">QuickSort3</span>(a, dest + <span class="number">1</span>, right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>⌨️<strong>代码解读：</strong> </p>
<ol>
<li><code>keyi</code> 是基准元素的索引，初始化为左边界 <code>left</code>，<code>dest</code> 指针用于标记小于基准元素的元素应该放置的位置，初始化为左边界 <code>left</code>，<code>cur</code> 指针用于遍历数组，初始化为 <code>left + 1</code></li>
<li>如果 <code>cur</code> 位置的值小于基准值，要和 <code>dest</code> 后面的元素进行交换，但是有可能 <code>dest</code> 后面就是 <code>cur</code>，所以我们可以让 <code>dest</code> 先 <code>++</code> ，再和 <code>cur</code> 比较，如果 <code>++dest == cur</code>，说明它们暂时指向同一个元素，无需交换；如果 <code>++dest != cur</code>，说明它们不指向同一个元素，直接交换</li>
</ol>
<p>🖱️<strong>复杂度分析：</strong></p>
<p>• <strong>时间复杂度：</strong></p>
<p>○ <strong>最好情况：</strong> 当每次选择的基准元素都能将数组均匀地分成两部分时，递归树的深度为 <code>log n</code> ，每层需要处理的元素总数为 <code>n</code>，因此总的时间复杂度为 <code>O(n * log n)</code></p>
<p>○ <strong>最坏情况：</strong> 最坏情况下，快速排序的时间复杂度会退化为 <code>O(n²)</code></p>
<p>○ <strong>平均情况：</strong> 时间复杂度为 <code>O(n * log n)</code></p>
<p>• <strong>空间复杂度：</strong> 时间复杂度为 <code>O(log n)</code></p>
<p><strong>总结：</strong> <code>快速排序整体的综合性能和使用场景都是比较好的，所以才敢叫快速排序</code></p>
<h3 id="非递归实现"><a href="#非递归实现" class="headerlink" title="非递归实现"></a>非递归实现</h3><p> 因为上面的三种方法均涉及递归，考虑到递归太多数据会导致<code>栈溢出的风险</code>，所以<code>非递归实现快排</code>也很重要</p>
<p>那么根据我们学过的<code>栈</code>发现其原理：<code>先进后出</code>，比较符合我们排序的效果</p>
<p>这里我们引入栈的头文件和源文件</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/145672800">【初阶数据结构】先来后到的秩序：栈和队列</a></p>
</blockquote>
<p> 💻<strong>排序实现：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">PartSort</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (left &gt;= right)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> randi = left + (<span class="built_in">rand</span>() % (right - left + <span class="number">1</span>));</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[left], &amp;a[randi]);</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> keyi = left;</span><br><span class="line">	<span class="type">int</span> dest = left, cur = left + <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (cur &lt;= right)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (a[cur] &lt; a[keyi] &amp;&amp; ++dest != cur)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">Swap</span>(&amp;a[cur], &amp;a[dest]);</span><br><span class="line">		&#125;</span><br><span class="line">		cur++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">Swap</span>(&amp;a[keyi], &amp;a[dest]);</span><br><span class="line">	<span class="keyword">return</span> dest;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">QuickSortNonR</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	ST st;</span><br><span class="line">	<span class="built_in">STInit</span>(&amp;st);</span><br><span class="line">	<span class="built_in">STPush</span>(&amp;st, right);</span><br><span class="line">	<span class="built_in">STPush</span>(&amp;st, left);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">while</span> (<span class="built_in">STEmpty</span>(&amp;st))</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="type">int</span> begin = <span class="built_in">STTop</span>(&amp;st);</span><br><span class="line">		<span class="built_in">STPop</span>(&amp;st);</span><br><span class="line">		<span class="type">int</span> end = <span class="built_in">STTop</span>(&amp;st);</span><br><span class="line">		<span class="built_in">STPop</span>(&amp;st);</span><br><span class="line"></span><br><span class="line">		<span class="type">int</span> keyi = <span class="built_in">PartSort</span>(a, begin, end);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (keyi + <span class="number">1</span> &lt; end)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">STPush</span>(&amp;st, end);</span><br><span class="line">			<span class="built_in">STPush</span>(&amp;st, keyi + <span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (begin &lt; keyi - <span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">STPush</span>(&amp;st, keyi - <span class="number">1</span>);</span><br><span class="line">			<span class="built_in">STPush</span>(&amp;st, begin);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">STDestroy</span>(&amp;st);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>代码解读：</strong> </p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/72049c69d504425b8355b37b3a54b100.png" alt="在这里插入图片描述"></p>
<ol>
<li>将初始的排序区间 <code>[left, right]</code> 压入栈中。注意，先压入右边界 <code>right</code>，再压入左边界 <code>left</code>，后续出栈时会先得到左边界，符合后续处理逻辑</li>
<li>从栈中弹出一个区间 <code>[begin, end]</code>，先弹出的是左边界 <code>begin</code>，再弹出右边界 <code>end</code></li>
<li>调用 <code>PartSort</code> 函数对当前区间 <code>[begin, end]</code> 进行分区操作，得到基准元素的最终位置 <code>keyi</code></li>
<li>根据基准元素的位置 <code>keyi</code>，将左右子区间压入栈中。如果基准元素右边还有元素<code>（keyi + 1 &lt; end）</code>，则将右子区间 <code>[keyi + 1, end]</code> 压入栈；如果基准元素左边还有元素<code>（begin &lt; keyi - 1）</code>，则将左子区间 <code>[begin, keyi - 1]</code> 压入栈。这样后续会继续对这些子区间进行排序</li>
</ol>
<p>🔥<strong>值得注意的是：</strong> 非递归的方式本质上就是借助栈来存区间，然后 <code>PartSort(a, begin, end)</code> 会对数进行交换排序，进行实质的交换</p>
<h1 id="归并排序（MergeSort）"><a href="#归并排序（MergeSort）" class="headerlink" title="归并排序（MergeSort）"></a>归并排序（MergeSort）</h1><h2 id="递归实现"><a href="#递归实现" class="headerlink" title="递归实现"></a>递归实现</h2><p><strong>动图理解：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/008068004b874760ae466a357f0175b2.gif" alt="请添加图片描述"></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/fd9eb767e96a4fa4bb9d1dd50bc5fa81.png" alt="在这里插入图片描述"><br>假设有这么个区间，两个有序区间，就是不断对两个移动指针比较，把较小的数插入到新空间，形成新的有序序列，然后再赋值回原来的空间</p>
<p>💻<strong>排序实现：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> _MergeSort(<span class="type">int</span>* a, <span class="type">int</span> begin, <span class="type">int</span> end, <span class="type">int</span>* tmp)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">if</span> (begin &gt;= end)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> mid = (begin + end) / <span class="number">2</span>;</span><br><span class="line">	_MergeSort(a, begin, mid, tmp);</span><br><span class="line">	_MergeSort(a, mid + <span class="number">1</span>, end, tmp);</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin1 = begin, end1 = mid;</span><br><span class="line">	<span class="type">int</span> begin2 = mid + <span class="number">1</span>, end2 = end;</span><br><span class="line">	<span class="type">int</span> i = begin;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">while</span> (begin1 &lt;= end1 &amp;&amp; begin2 &lt;= end2)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (a[begin1] &lt; a[begin2])</span><br><span class="line">		&#123;</span><br><span class="line">			tmp[i++] = a[begin1++];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			tmp[i++] = a[begin2++];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">while</span> (begin1 &lt;= end1)</span><br><span class="line">	&#123;</span><br><span class="line">		tmp[i++] = a[begin1++];</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">while</span> (begin2 &lt;= end2)</span><br><span class="line">	&#123;</span><br><span class="line">		tmp[i++] = a[begin2++];</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">memcpy</span>(a + begin, tmp + begin, <span class="built_in">sizeof</span>(<span class="type">int</span>) * (end - begin + <span class="number">1</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">MergeSort</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span>* tmp = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * n);</span><br><span class="line">	<span class="keyword">if</span> (tmp == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">perror</span>(<span class="string">&quot;malloc fail&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	_MergeSort(a, <span class="number">0</span>, n - <span class="number">1</span>, tmp);</span><br><span class="line">	<span class="built_in">free</span>(tmp);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>代码解读：</strong> </p>
<ol>
<li>计算中间索引 <code>mid</code>，将当前数组分成两个子数组，分别递归调用 <code>_MergeSort</code> 函数对左右子数组进行排序，<code>从最下面的子数组依次往上归并</code></li>
<li>初始化两个指针 <code>begin1</code> 和 <code>begin2</code> 分别指向左右子数组的起始位置，<code>end1</code> 和 <code>end2</code> 指向左右子数组的结束位置</li>
<li>比较 <code>a[begin1]</code> 和 <code>a[begin2]</code> 的大小，将较小的元素放入临时数组 <code>tmp</code> 中，并将相应的指针后移</li>
<li>当其中一个子数组遍历完后，将另一个子数组中剩余的元素依次放入临时数组 <code>tmp</code> 中</li>
<li>使用 <code>memcpy</code> 函数将临时数组 <code>tmp</code> 中排好序的元素复制回原数组 <code>a</code> 中</li>
</ol>
<p>🔥<strong>值得注意的是：</strong> <code>memcpy(a + begin, tmp + begin, sizeof(int) * (end - begin + 1))</code>，而不是 <code>memcpy(a, tmp, sizeof(int) * (end - begin + 1))</code>，为了在临时数组中准确找到当前子数组合并结果的起始位置，以便将排好序的数据正确地复制回原数组</p>
<h2 id="非递归实现-1"><a href="#非递归实现-1" class="headerlink" title="非递归实现"></a>非递归实现</h2><p>同理，为了<code>避免栈溢出</code>，<code>归并排序</code>也有<code>非递归实现</code></p>
<p><strong>为什么不用栈处理？</strong></p>
<blockquote>
<p><code>栈的非递归实现</code>其实是类似于<code>前序遍历</code>的，而<code>归并的非递归实现</code>类似于<code>后序遍历</code></p>
</blockquote>
<p>💻<strong>排序实现：</strong></p>
<h3 id="一次性全部拷贝回去：memcpy-a-tmp-sizeof-int-n"><a href="#一次性全部拷贝回去：memcpy-a-tmp-sizeof-int-n" class="headerlink" title="一次性全部拷贝回去：memcpy(a, tmp, sizeof(int) * n)"></a>一次性全部拷贝回去：memcpy(a, tmp, sizeof(int) * n)</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">MergeSortNonR1</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span>* tmp = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * n);</span><br><span class="line">	<span class="keyword">if</span> (tmp == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">perror</span>(<span class="string">&quot;malloc fail&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> gap = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (gap &lt; n)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i += <span class="number">2</span> * gap)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="type">int</span> begin1 = i, end1 = i + gap - <span class="number">1</span>;</span><br><span class="line">			<span class="type">int</span> begin2 = i + gap, end2 = i + <span class="number">2</span> * gap - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">if</span> (end1 &gt;= n)</span><br><span class="line">			&#123;</span><br><span class="line">				end1 = n - <span class="number">1</span>;</span><br><span class="line">				begin2 = n;</span><br><span class="line">				end2 = n - <span class="number">1</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (begin2 &gt;= n)</span><br><span class="line">			&#123;</span><br><span class="line">				begin2 = n;</span><br><span class="line">				end2 = n - <span class="number">1</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (end2 &gt;= n)</span><br><span class="line">			&#123;</span><br><span class="line">				end2 = n - <span class="number">1</span>;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="type">int</span> j = i;</span><br><span class="line">			<span class="keyword">while</span> (begin1 &lt;= end1 &amp;&amp; begin2 &lt;= end2)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">if</span> (a[begin1] &lt; a[begin2])</span><br><span class="line">				&#123;</span><br><span class="line">					tmp[j++] = a[begin1++];</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span></span><br><span class="line">				&#123;</span><br><span class="line">					tmp[j++] = a[begin2++];</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">while</span> (begin1 &lt;= end1)</span><br><span class="line">			&#123;</span><br><span class="line">				tmp[j++] = a[begin1++];</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">while</span> (begin2 &lt;= end2)</span><br><span class="line">			&#123;</span><br><span class="line">				tmp[j++] = a[begin2++];</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="built_in">memcpy</span>(a, tmp, <span class="built_in">sizeof</span>(<span class="type">int</span>) * n);</span><br><span class="line">		&#125;</span><br><span class="line">		gap *= <span class="number">2</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">free</span>(tmp);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>⌨️<strong>代码解读：</strong><br><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/a141e4d6ee944d0588944b95df65911d.png" alt="在这里插入图片描述"><br><code>gap</code> 表示一组有多少个数据，<code>gap = 1</code> 时一个一个归并，<code>gap = 2</code> 时两个两个归并，依次向后推，不断扩大 <code>gap</code> 实现有序</p>
<p>根据规律写出 <code>int begin1 = i, end1 = i + gap - 1</code>；<code>int begin2 = i + gap, end2 = i + 2 * gap - 1</code>；</p>
<p>但是我们发现这套规律只适用于<code>偶数个数的归并</code>，当为奇数时会出现&#96;多出来一个数无法进行归并的情况，所以我们要针对这种情况进行修正</p>
<ol>
<li><strong>end1 越界示例</strong><br>假设我们有一个长度 <code>n = 5</code> 的数组 <code>arr = [1, 2, 3, 4, 5]</code>，当 <code>gap = 4</code> 时，开始进行合并操作</li>
</ol>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/bf564d83058547beb1081c356035215c.png" alt="在这里插入图片描述"></p>
<p><strong>计算过程：</strong></p>
<p>当 <code>i = 0</code> 时：<code>begin1 = i = 0</code>，<code>end1 = i + gap - 1 = 0 + 4 - 1 = 3</code>，这是正常的，因为数组索引 <code>3</code> 在有效范围内（数组索引范围是 <code>0</code> 到 <code>4</code>）</p>
<p>当 <code>i = 4</code> 时：<code>begin1 = i = 4</code>，<code>end1 = i + gap - 1 = 4 + 4 - 1 = 7</code>，而数组的最大有效索引是 <code>4</code>，此时 <code>end1</code> 超出了数组的边界，出现越界情况</p>
<p><strong>修正方法：</strong> <code>end1 = n - 1</code>，<code>begin2 = n</code>，<code>end2 = n - 1</code>，因为是整体赋值，让有效的数据按原路返回，后面的修正为一个不存在的区间，也就不会归并了，那么就有个问题，后面的数不就无序了吗？其实前面的排序保证了其有序性，在 gap 进一步扩大的过程中会将其逐步变为有序</p>
<ol start="2">
<li><strong>begin2 越界示例</strong><br>同样使用长度 <code>n = 5</code> 的数组 <code>arr = [1, 2, 3, 4, 5]</code>，当 <code>gap = 3</code> 时进行分析</li>
</ol>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/c933c90c07f54dfd9432885887236e30.png" alt="在这里插入图片描述"></p>
<p><strong>计算过程：</strong></p>
<p>当 <code>i = 2</code> 时：<code>begin1 = i = 2</code>，<code>end1 = i + gap - 1 = 2 + 3 - 1 = 4</code>，这是正常的，<code>begin2 = i + gap = 2 + 3 = 5</code>，数组的最大有效索引是 <code>4</code>，所以 <code>begin2</code> 超出了数组的边界，出现越界情况</p>
<p><strong>修正方法：</strong> 同 <code>end1</code> 越界处理情况相同</p>
<ol start="3">
<li><strong>end2 越界示例</strong></li>
</ol>
<p>还是以长度 <code>n = 5</code> 的数组 <code>arr = [1, 2, 3, 4, 5]</code> 为例，当 <code>gap = 3</code> 时进行分析</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/22d2efb3e5a44827825103f8a98325a7.png" alt="在这里插入图片描述"></p>
<p><strong>计算过程：</strong></p>
<p>当 <code>i = 0</code> 时：<code>begin1 = i = 0</code>，<code>end1 = i + gap - 1 = 0 + 3 - 1 = 2</code>，<code>begin2 = i + gap = 0 + 3 = 3</code>，<code>end2 = i + 2 * gap - 1 = 0 + 2 * 3 - 1 = 5</code>，数组的最大有效索引是 <code>4</code>，所以 <code>end2</code> 超出了数组的边界，出现越界情况</p>
<p><strong>修正方法：</strong> <code>end2 = n - 1</code>，将有效数据纳入进行排序，剩余的数在 <code>gap</code> 扩大时会得到处理</p>
<h3 id="分批次拷贝回去：memcpy-a-i-tmp-i-sizeof-int-end2-i-1"><a href="#分批次拷贝回去：memcpy-a-i-tmp-i-sizeof-int-end2-i-1" class="headerlink" title="分批次拷贝回去：memcpy(a + i, tmp + i, sizeof(int) * (end2 - i + 1))"></a>分批次拷贝回去：memcpy(a + i, tmp + i, sizeof(int) * (end2 - i + 1))</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">MergeSortNonR2</span><span class="params">(<span class="type">int</span>* a, <span class="type">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span>* tmp = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * n);</span><br><span class="line">	<span class="keyword">if</span> (tmp == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">perror</span>(<span class="string">&quot;malloc fail&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> gap = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (gap &lt; n)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i += <span class="number">2</span> * gap)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="type">int</span> begin1 = i, end1 = i + gap - <span class="number">1</span>;</span><br><span class="line">			<span class="type">int</span> begin2 = i + gap, end2 = i + <span class="number">2</span> * gap - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">if</span> (end1 &gt;= n || begin2 &gt;= n)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (end2 &gt;= n)</span><br><span class="line">			&#123;</span><br><span class="line">				end2 = n - <span class="number">1</span>;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="type">int</span> j = i;</span><br><span class="line">			<span class="keyword">while</span> (begin1 &lt;= end1 &amp;&amp; begin2 &lt;= end2)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">if</span> (a[begin1] &lt; a[begin2])</span><br><span class="line">				&#123;</span><br><span class="line">					tmp[j++] = a[begin1++];</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span></span><br><span class="line">				&#123;</span><br><span class="line">					tmp[j++] = a[begin2++];</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">while</span> (begin1 &lt;= end1)</span><br><span class="line">			&#123;</span><br><span class="line">				tmp[j++] = a[begin1++];</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">while</span> (begin2 &lt;= end2)</span><br><span class="line">			&#123;</span><br><span class="line">				tmp[j++] = a[begin2++];</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="built_in">memcpy</span>(a + i, tmp + i, <span class="built_in">sizeof</span>(<span class="type">int</span>) * (end2 - i + <span class="number">1</span>));</span><br><span class="line">		&#125;</span><br><span class="line">		gap *= <span class="number">2</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">free</span>(tmp);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>代码解读：</strong> </p>
<p><strong>一次性拷贝回去需要调整 end1、begin1 等边界：</strong></p>
<blockquote>
<p>一次性拷贝回去意味着我们要把合并好的结果一次性从临时数组 <code>tmp</code> 复制回原数组 <code>a</code>。在这个过程中，如果出现越界情况，比如 <code>end1</code> 或 <code>end2</code> 超出了数组长度，我们需要调整这些边界，以确保只处理有效的数组元素，避免访问非法内存</p>
</blockquote>
<p><strong>分批次拷贝回去直接 break：</strong></p>
<blockquote>
<p>分批次拷贝回去通常是指在发现越界情况时，由于后续没有有效的子数组可供合并，直接终止当前的合并操作，等待下一轮更大的 <code>gap</code> 再处理剩余元素。这种方式简化了越界处理逻辑，因为不需要对越界的边界进行复杂的调整</p>
</blockquote>
<p><strong>end1、begin2 越界：</strong> <code>break</code>，等待 <code>gap</code> 增大时处理未处理的数据</p>
<p><strong>end2 越界：</strong> 和一次性拷贝的处理相同</p>
<p>🔥<strong>值得注意的是：</strong> <code>memcpy(a + i, tmp + i, sizeof(int) * (end2 - i + 1)) </code>不能写成 <code>memcpy(a + begin1, tmp + begin1, sizeof(int) * (end2 - begin1 + 1))</code>，因为 <code>begin1</code> 被移动了，<code>i</code> 才是原来的初始位置</p>
<h1 id="6-排序复杂度及效率对比"><a href="#6-排序复杂度及效率对比" class="headerlink" title="6.排序复杂度及效率对比"></a>6.排序复杂度及效率对比</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/8dc0c902262b4c0d809d2723b26aa11b.jpeg" alt="请添加图片描述"></p>
<p>💻<strong>测试代码：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">TestOP</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">srand</span>(<span class="built_in">time</span>(<span class="literal">NULL</span>));</span><br><span class="line">	<span class="type">const</span> <span class="type">int</span> N = <span class="number">100000</span>;</span><br><span class="line">	<span class="type">int</span>* a1 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a2 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a3 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a4 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a5 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a6 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a7 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a8 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a9 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a10 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a11 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line">	<span class="type">int</span>* a12 = (<span class="type">int</span>*)<span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(<span class="type">int</span>) * N);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; N; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		a1[i] = <span class="built_in">rand</span>();</span><br><span class="line">		a2[i] = a1[i];</span><br><span class="line">		a3[i] = a1[i];</span><br><span class="line">		a4[i] = a1[i];</span><br><span class="line">		a5[i] = a1[i];</span><br><span class="line">		a6[i] = a1[i];</span><br><span class="line">		a7[i] = a1[i];</span><br><span class="line">		a8[i] = a1[i];</span><br><span class="line">		a9[i] = a1[i];</span><br><span class="line">		a10[i] = a1[i];</span><br><span class="line">		a11[i] = a1[i];</span><br><span class="line">		a12[i] = a1[i];</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin1 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">InsertSort</span>(a1, N);</span><br><span class="line">	<span class="type">int</span> end1 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin2 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">ShellSort</span>(a2, N);</span><br><span class="line">	<span class="type">int</span> end2 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin3 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">SelectSort</span>(a3, N);</span><br><span class="line">	<span class="type">int</span> end3 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin4 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">HeapSort</span>(a4, N);</span><br><span class="line">	<span class="type">int</span> end4 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin5 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">QuickSort1</span>(a5, <span class="number">0</span>, N - <span class="number">1</span>);</span><br><span class="line">	<span class="type">int</span> end5 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin8 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">QuickSort2</span>(a8, <span class="number">0</span>, N - <span class="number">1</span>);</span><br><span class="line">	<span class="type">int</span> end8 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin9 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">QuickSort3</span>(a9, <span class="number">0</span>, N - <span class="number">1</span>);</span><br><span class="line">	<span class="type">int</span> end9 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin10 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">QuickSortNonR</span>(a9, <span class="number">0</span>, N - <span class="number">1</span>);</span><br><span class="line">	<span class="type">int</span> end10 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin6 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">MergeSort</span>(a6, N);</span><br><span class="line">	<span class="type">int</span> end6 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin11 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">MergeSortNonR1</span>(a11, N);</span><br><span class="line">	<span class="type">int</span> end11 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin12 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">MergeSortNonR1</span>(a12, N);</span><br><span class="line">	<span class="type">int</span> end12 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> begin7 = <span class="built_in">clock</span>();</span><br><span class="line">	<span class="built_in">BubbleSort</span>(a7, N);</span><br><span class="line">	<span class="type">int</span> end7 = <span class="built_in">clock</span>();</span><br><span class="line"></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;InsertSort:%d\n&quot;</span>, end1 - begin1);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;ShellSort:%d\n&quot;</span>, end2 - begin2);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;SelectSort:%d\n&quot;</span>, end3 - begin3);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;HeapSort:%d\n&quot;</span>, end4 - begin4);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;BubbleSort:%d\n&quot;</span>, end7 - begin7);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;QuickSort1:%d\n&quot;</span>, end5 - begin5);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;QuickSort2:%d\n&quot;</span>, end8 - begin8);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;QuickSort3:%d\n&quot;</span>, end9 - begin9);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;QuickSortNonR:%d\n&quot;</span>, end10 - begin10);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;MergeSort:%d\n&quot;</span>, end6 - begin6);	</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;MergeSortNonR1:%d\n&quot;</span>, end11 - begin11);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;MergeSortNonR2:%d\n&quot;</span>, end12 - begin12);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="built_in">free</span>(a1);</span><br><span class="line">	<span class="built_in">free</span>(a2);</span><br><span class="line">	<span class="built_in">free</span>(a3);</span><br><span class="line">	<span class="built_in">free</span>(a4);</span><br><span class="line">	<span class="built_in">free</span>(a5);</span><br><span class="line">	<span class="built_in">free</span>(a6);</span><br><span class="line">	<span class="built_in">free</span>(a7);</span><br><span class="line">	<span class="built_in">free</span>(a8);</span><br><span class="line">	<span class="built_in">free</span>(a9);</span><br><span class="line">	<span class="built_in">free</span>(a10);</span><br><span class="line">	<span class="built_in">free</span>(a11);</span><br><span class="line">	<span class="built_in">free</span>(a12);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>⌨️<strong>测试结果：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e3f6e6a48ea3413e9449524337257e78.png" alt="在这里插入图片描述"></p>
<hr>
<h1 id="希望读者们多多三连支持"><a href="#希望读者们多多三连支持" class="headerlink" title="希望读者们多多三连支持"></a>希望读者们多多三连支持</h1><h1 id="小编会继续更新"><a href="#小编会继续更新" class="headerlink" title="小编会继续更新"></a>小编会继续更新</h1><h1 id="你们的鼓励就是我前进的动力！"><a href="#你们的鼓励就是我前进的动力！" class="headerlink" title="你们的鼓励就是我前进的动力！"></a>你们的鼓励就是我前进的动力！</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/b199b4a8406e4021801be6f012f45a37.gif" alt="请添加图片描述"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">澪贰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8B%EF%BC%89/">http://example.com/2025/02/25/初阶数据结构/排序（下）/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="http://example.com" target="_blank">澪贰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a><a class="post-meta__tags" href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">数据结构</a><a class="post-meta__tags" href="/tags/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/">排序算法</a><a class="post-meta__tags" href="/tags/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F/">快速排序</a><a class="post-meta__tags" href="/tags/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F/">归并排序</a></div><div class="post-share"><div class="social-share" data-image="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250225211552.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i>赞助</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related" href="/2025/02/28/%E8%AF%9D%E9%A2%98/%E5%A6%82%E4%BD%95%E9%AB%98%E6%95%88%E5%88%A9%E7%94%A8DeepSeek/" title="如何高效利用DeepSeek：深入探索AI搜索引擎的潜力"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e640e59c2f92482993b52c845adf7844.webp" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">如何高效利用DeepSeek：深入探索AI搜索引擎的潜力</div></div><div class="info-2"><div class="info-item-1">随着人工智能技术的飞速发展，传统的搜索引擎正逐步向更智能化、个性化的方向演进。作为一款基于深度学习的 AI 搜索引擎，DeepSeek（深度求索）不仅在理解用户意图方面展现出色，还通过集成丰富的知识图谱和提供多样化的信息类型，成为现代用户的信息获取利器。本文将详细分析如何高效利用 DeepSeek，探讨其核心技术、实际应用场景以及性能优化方法  深入理解DeepSeek的核心优势DeepSeek的基本功能与原理DeepSeek 作为一款 AI 搜索引擎，其核心在于语义理解和信息推荐能力。以下是其关键技术：  自然语言处理（NLP）： 通过深度学习模型，DeepSeek能够理解用户输入的语义意图，从而提供更相关的搜索结果  知识图谱集成： DeepSeek 内置了庞大的知识图谱，能够将信息进行链接和关联，帮助用户快速定位到所需内容  个性化推荐算法： 基于用户行为数据，DeepSeek 能够为每个用户提供高度定制的搜索结果   DeepSeek与传统搜索引擎的区别与传统搜索引擎相比，DeepSeek 有以下显著特点：  语义理解能力强：...</div></div></div></a><a class="pagination-related" href="/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8A%EF%BC%89/" title="【初阶数据结构】星河中的光影 “排” 象：排序（上）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250223152235.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">【初阶数据结构】星河中的光影 “排” 象：排序（上）</div></div><div class="info-2"><div class="info-item-1">排序的概念及分类 排序，就是使一串记录，按照其中的某个或某些关键字的大小，递增或递减的排列起来的操作  常见的排序算法的可以按如图所示分类：  以下所有的排序算法均以升序的方式实现 插入排序直接插入排序（InsertSort）直接插入排序是一种简单的插入排序法，其基本思想是： 把待排序的记录按其关键码值的大小逐个插入到一个已经排好序的有序序列中，直到所有的记录插入完为止，得到一个新的有序序列 简单来说我们平常玩的扑克牌游戏就是一种插入排序：  排序原理：  当插入第 i ( i &gt;= 1 ) 个元素时，前面的 array[0] ，array[1] ，… ，array[i-1] 已经排好序，此时用 array[i] 的排序码与 array[i - 1] ，array[i - 2] ，… 的排序码顺序进行比较，找到插入位置即将 array[i] 插入，原来位置上的元素顺序后移 动图理解：  💻排序实现： 123456789101112131415161718192021void InsertSort(int* a, int n)&#123;	for (int i = 1;...</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/2025/02/25/%E5%88%9D%E9%98%B6%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F%EF%BC%88%E4%B8%8A%EF%BC%89/" title="【初阶数据结构】星河中的光影 “排” 象：排序（上）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250223152235.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-25</div><div class="info-item-2">【初阶数据结构】星河中的光影 “排” 象：排序（上）</div></div><div class="info-2"><div class="info-item-1">排序的概念及分类 排序，就是使一串记录，按照其中的某个或某些关键字的大小，递增或递减的排列起来的操作  常见的排序算法的可以按如图所示分类：  以下所有的排序算法均以升序的方式实现 插入排序直接插入排序（InsertSort）直接插入排序是一种简单的插入排序法，其基本思想是： 把待排序的记录按其关键码值的大小逐个插入到一个已经排好序的有序序列中，直到所有的记录插入完为止，得到一个新的有序序列 简单来说我们平常玩的扑克牌游戏就是一种插入排序：  排序原理：  当插入第 i ( i &gt;= 1 ) 个元素时，前面的 array[0] ，array[1] ，… ，array[i-1] 已经排好序，此时用 array[i] 的排序码与 array[i - 1] ，array[i - 2] ，… 的排序码顺序进行比较，找到插入位置即将 array[i] 插入，原来位置上的元素顺序后移 动图理解：  💻排序实现： 123456789101112131415161718192021void InsertSort(int* a, int n)&#123;	for (int i = 1;...</div></div></div></a><a class="pagination-related" href="/2025/04/19/CPP%E8%BF%9B%E9%98%B6/%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91/" title="C++镌刻数据密码的树之铭文：二叉搜索树"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250407204529.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-19</div><div class="info-item-2">C++镌刻数据密码的树之铭文：二叉搜索树</div></div><div class="info-2"><div class="info-item-1">继数据结构的二叉树学习，本篇进行更进一步的搜索二叉树，是一种更为常见的结构 二叉搜索树的概念 二叉搜索树简单来说就是一个排序树  它是具有以下性质的二叉树:  若它的左子树不为空，则左子树上所有节点的值都小于根节点的值 若它的右子树不为空，则右子树上所有节点的值都大于根节点的值 它的左右子树也分别为二叉搜索树  🔥值得注意的是： 每棵子树都满足该性质 二叉搜索树的实现二叉搜索树的结构12345678910111213template&lt;class K&gt;struct BSTreeNode&#123;	BSTreeNode&lt;K&gt;* _left;	BSTreeNode&lt;K&gt;* _right;	K _key;	BSTreeNode(const K&amp; key)		:_left(nullptr)		,_right(nullptr)		,_key(key)	&#123; &#125;&#125;;  _left： 指向左子节点的指针。 _right： 指向右子节点的指针。 _key：...</div></div></div></a><a class="pagination-related" href="/2025/04/25/CPP%E8%BF%9B%E9%98%B6/%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91OJ/" title="C++穿梭树影间的智慧博弈：二叉搜索树OJ"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250425235842.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-25</div><div class="info-item-2">C++穿梭树影间的智慧博弈：二叉搜索树OJ</div></div><div class="info-2"><div class="info-item-1">本篇对搜索二叉树常见的面试OJ进行了总结，方便对常见的数据结构使用方法进行总结 根据二叉树创建字符串✏️题目描述：  ✏️示例：   传送门： 根据二叉树创建字符串  题解:  观察示例可以知道，无论是左为空还是左为不为空，都要添加括号，所以直接递归下去，右分支则可以根据情况省略括号 💻代码实现： 1234567891011121314151617181920212223242526272829class Solution &#123;public:    string tree2str(TreeNode* root)     &#123;        if (root == nullptr)        &#123;            return &quot; &quot;;        &#125;        string str = to_string(root-&gt;val);        if (root-&gt;left || root-&gt;right)        &#123;            str +=...</div></div></div></a><a class="pagination-related" href="/2025/01/01/%E4%BC%98%E9%80%89%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%83%EF%BC%88%E4%B8%8A%EF%BC%89/" title="【优选算法】Binary-Blade：二分查找的算法刃（上）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241226001431.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-01-01</div><div class="info-item-2">【优选算法】Binary-Blade：二分查找的算法刃（上）</div></div><div class="info-2"><div class="info-item-1">概念解析s🚩什么是二分查找算法？ 每次比较中间元素，通过判断中间元素与目标元素的大小关系，将搜索区间缩小一半，持续这个过程，直至找到目标元素或者确定目标元素不存在 二分查找的简单模版✏️题目描述：  ✏️示例：   传送门：二分查找  题解: 在一个无论是有序还是无序的数列里，一般最先想到的就是暴力解法遍历一遍，然后符合条件则成立，这种方法固然是好用，但是一般在搜索数据的过程中，数据量庞大，O(n)的时间复杂度还是太大了，那么这时候就要使用时间复杂度为O(log n)的二分查找 💻第一步： 二分查找说的就是折中查找，那么二段性就是重要的第一步，找出左右区间不同的地方  比如这题就是 target 的左区间小于它，右区间大于它，根据这个特性不断调整left和right的位置，接下来看一下具体实现 💻第二步： 不断循环算出mid的值，与target作比较，如果大于target，说明mid所指位置及后面的数都不是符合target的数，right = mid - 1；如果小于target，说明mid所指位置及前面的数都不是符合target的数， left = mid +...</div></div></div></a><a class="pagination-related" href="/2025/01/06/%E4%BC%98%E9%80%89%E7%AE%97%E6%B3%95/%E4%BD%8D%E8%BF%90%E7%AE%97%E7%9A%84%E7%AE%97%E6%B3%95%E4%B9%8B%E9%81%93/" title="【优选算法】Bit-Samurai：位运算的算法之道"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250101234601.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-01-06</div><div class="info-item-2">【优选算法】Bit-Samurai：位运算的算法之道</div></div><div class="info-2"><div class="info-item-1">常见位运算总结基础位运算符号这六个位运算符是实现位运算算法的重要运算符，在C语言阶段有详细的介绍过  传送门：关于我、重生到500年前凭借C语言改变世界科技vlog.10——进制转化&amp;&amp;操作符进阶  记法如图所示，强调一下什么是无进位相加？  异或运算的规则决定了它天然契合无进位相加的概念异或运算在比较两个二进制位时，0 ^ 0 &#x3D; 0，0 ^ 1 &#x3D; 1 ，1 ^ 0 &#x3D; 1， 1 ^ 1 &#x3D; 0只是单纯对比两个数在每一位上的值，将不同的视为 1，相同的视为 0 ，不涉及向高位进位  给一个数 n，确定它的二进制表示中的第 x 位是 0 还是 1 约定二进制位从右到左，为最低位到最高位，定义为从0到31，为的就是对应右移x位刚好对应第x位。所以将要比较的数 n 的第x位右移x位，与1按位与&amp;，如果是0，第x位为0；如果是1，第x位是1 将一个数 n 的二进制表示的第 x 位修改成 1 要修改数n第x位为1就不能破坏原来的数，所以将1移动x位，与1按位或|，只修改了我们想要修改的那一位 将一个数 n...</div></div></div></a><a class="pagination-related" href="/2025/01/13/%E4%BC%98%E9%80%89%E7%AE%97%E6%B3%95/%E5%88%86%E6%B2%BB-%E5%BF%AB%E6%8E%92%E7%9A%84%E7%AE%97%E6%B3%95%E4%B9%8B%E8%BF%B7/" title="【优选算法】D&amp;C-Quicksort-Mysteries：分治-快排的算法之迷"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250110170433.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-01-13</div><div class="info-item-2">【优选算法】D&amp;C-Quicksort-Mysteries：分治-快排的算法之迷</div></div><div class="info-2"><div class="info-item-1">概念解析🚩什么是分治-快排？  分治是核心思想，即将大问题拆解成形式相同的小问题来处理，从待排序数组里挑出一个元素当作基准，设置两个指针，一个从数组开头，一个从末尾出发，先把一个无序的数组划分成两个子数组，接着分别处理这两个子数组，随着递归深入，子数组越来越小，最终每个子数组只剩 1 个元素时，天然有序，整个大数组也就完成排序  颜色分类✏️题目描述：  ✏️示例：   传送门：颜色分类  题解: 对于排序的题目，根据前些的学习我们一般都是想到冒泡排序等基础算法，但是此类算法对于带有重复性的排序很不友好，还是太慢了，因此对于这道题，也是一道经典的荷兰国旗问题，使用类似双指针算法中的移动零那道题的方法，划分区间比较排序，衍生出来了一种三划分排序算法，也叫作快速排序 💻第一步：  首先我们这题要排序的是0、1、2三个数字，所以划分为三个区间，分别是小于1的区间，等于1的区间，大于1的区间。left表示标记左区间的指针，i表示扫描区间指针，right表示标记右区间的指针 💻第二步：  前提条件left = -1, right =...</div></div></div></a></div></div><hr class="custom-hr"/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="card-info-avatar"><div class="avatar-img"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-status-box"><div class="author-status"><g-emoji class="g-emoji" alias="palm_tree" fallback-src="https://lskypro.acozycotage.net/LightPicture/2022/12/fe1dc0402e623096.jpg">🤯</g-emoji><span>头脑风暴中</span></div></div></div><div class="author-info-name">澪贰</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ZeroCoder-Zhang"><i></i><span>🛫下一站--github</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/ZeroCoder-Zhang" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:1478943685@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><center><b>--- 主域名 ---<br><a target="_blank" rel="noopener" href="https://general.zzh-blog.club/" title="主域名链接" class="anno_content"><font color="#5ea6e5">general.zzh-blog.club</font></a></b></center><center><b>--- 推广学习交流(Wechat) ---<br><a target="_blank" rel="noopener" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/微信扫码加好友.png" title="微信图片" class="anno_content"><font color="#5ea6e5">zzh1478943685(备注来意)</font></a></b></center></div><div id="welcome-info"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%A4%E6%8D%A2%E6%8E%92%E5%BA%8F"><span class="toc-number">1.</span> <span class="toc-text">交换排序</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F%EF%BC%88BubbleSort%EF%BC%89"><span class="toc-number">1.1.</span> <span class="toc-text">冒泡排序（BubbleSort）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%EF%BC%88QuickSort%EF%BC%89"><span class="toc-number">1.2.</span> <span class="toc-text">快速排序（QuickSort）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#hoare%E7%89%88%E6%9C%AC"><span class="toc-number">1.2.1.</span> <span class="toc-text">hoare版本</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8C%96%E5%9D%91%E6%B3%95"><span class="toc-number">1.2.2.</span> <span class="toc-text">挖坑法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E5%90%8E%E6%8C%87%E9%92%88%E6%B3%95"><span class="toc-number">1.2.3.</span> <span class="toc-text">前后指针法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.2.4.</span> <span class="toc-text">非递归实现</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F%EF%BC%88MergeSort%EF%BC%89"><span class="toc-number">2.</span> <span class="toc-text">归并排序（MergeSort）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.1.</span> <span class="toc-text">递归实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0-1"><span class="toc-number">2.2.</span> <span class="toc-text">非递归实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E6%AC%A1%E6%80%A7%E5%85%A8%E9%83%A8%E6%8B%B7%E8%B4%9D%E5%9B%9E%E5%8E%BB%EF%BC%9Amemcpy-a-tmp-sizeof-int-n"><span class="toc-number">2.2.1.</span> <span class="toc-text">一次性全部拷贝回去：memcpy(a, tmp, sizeof(int) * n)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E6%89%B9%E6%AC%A1%E6%8B%B7%E8%B4%9D%E5%9B%9E%E5%8E%BB%EF%BC%9Amemcpy-a-i-tmp-i-sizeof-int-end2-i-1"><span class="toc-number">2.2.2.</span> <span class="toc-text">分批次拷贝回去：memcpy(a + i, tmp + i, sizeof(int) * (end2 - i + 1))</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#6-%E6%8E%92%E5%BA%8F%E5%A4%8D%E6%9D%82%E5%BA%A6%E5%8F%8A%E6%95%88%E7%8E%87%E5%AF%B9%E6%AF%94"><span class="toc-number">3.</span> <span class="toc-text">6.排序复杂度及效率对比</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B8%8C%E6%9C%9B%E8%AF%BB%E8%80%85%E4%BB%AC%E5%A4%9A%E5%A4%9A%E4%B8%89%E8%BF%9E%E6%94%AF%E6%8C%81"><span class="toc-number">4.</span> <span class="toc-text">希望读者们多多三连支持</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B0%8F%E7%BC%96%E4%BC%9A%E7%BB%A7%E7%BB%AD%E6%9B%B4%E6%96%B0"><span class="toc-number">5.</span> <span class="toc-text">小编会继续更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%A0%E4%BB%AC%E7%9A%84%E9%BC%93%E5%8A%B1%E5%B0%B1%E6%98%AF%E6%88%91%E5%89%8D%E8%BF%9B%E7%9A%84%E5%8A%A8%E5%8A%9B%EF%BC%81"><span class="toc-number">6.</span> <span class="toc-text">你们的鼓励就是我前进的动力！</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250728114434.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"/></a><div class="content"><a class="title" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用">【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用</a><time datetime="2025-07-28T13:41:39.000Z" title="发表于 2025-07-28 21:41:39">2025-07-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250713233449.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux权限"/></a><div class="content"><a class="title" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限">【Linux操作系统】简学深悟启示录：Linux权限</a><time datetime="2025-07-13T22:00:00.000Z" title="发表于 2025-07-14 06:00:00">2025-07-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250705182234.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux基本指令"/></a><div class="content"><a class="title" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令">【Linux操作系统】简学深悟启示录：Linux基本指令</a><time datetime="2025-07-07T12:31:51.000Z" title="发表于 2025-07-07 20:31:51">2025-07-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250608235413.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（下）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）">【前端基础】层叠宇宙的代码旅人：css（下）</a><time datetime="2025-06-23T07:47:50.000Z" title="发表于 2025-06-23 15:47:50">2025-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/909e58aa338befce9e0b2e4e683d50c.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（中）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）">【前端基础】层叠宇宙的代码旅人：css（中）</a><time datetime="2025-06-23T07:44:20.000Z" title="发表于 2025-06-23 15:44:20">2025-06-23</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 - 2025 By 澪贰</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.3.5</a></div><div class="footer_custom_text">🏃‍➡️不是遇到同行伙伴再出发，而是出发后的路上遇到志同道合的人。<p></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src= "" data-lazy-src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="前往评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"><span id="percent">0</span><span>%</span></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>(() => {
  const isShuoshuo = GLOBAL_CONFIG_SITE.pageType === 'shuoshuo'
  const option = null

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(res => {
      countELement.textContent = res[0].count
    }).catch(err => {
      console.error(err)
    })
  }

  const init = (el = document, path = location.pathname) => {
    twikoo.init({
      el: el.querySelector('#twikoo-wrap'),
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
        placeholder: "|´・ω・)ノ嘿~都看到这儿了\n确定不评论一下再走嘛？\n(点完发送按钮等几秒哦~)",
        nicknamePlaceholder: "昵称/笔名",
        emailPlaceholder: "邮箱（不会公开）",
        urlPlaceholder: "个人站点",
      onCommentLoaded: () => {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      },
      ...option,
      path: isShuoshuo ? path : (option && option.path) || path
    })

    

    isShuoshuo && (window.shuoshuoComment.destroyTwikoo = () => {
      if (el.children.length) {
        el.innerHTML = ''
        el.classList.add('no-comment')
      }
    })
  }

  const loadTwikoo = (el, path) => {
    if (typeof twikoo === 'object') setTimeout(() => init(el, path), 0)
    else btf.getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(() => init(el, path))
  }

  if (isShuoshuo) {
    'Twikoo' === 'Twikoo'
      ? window.shuoshuoComment = { loadComment: loadTwikoo }
      : window.loadOtherComment = loadTwikoo
    return
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = loadTwikoo
  }
})()</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/cat.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script async src="/js/title.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer data-pjax src="/js/readPercent.js"></script><div class="aplayer no-destroy" data-id="8459282733" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-listmaxheight=400px data-order="random"> </div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async data-pjax src="/js/txmap.js"></script><script src="source/js/统计图颜色适配.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script>(() => {
  const destroyAplayer = () => {
    if (window.aplayers) {
      for (let i = 0; i < window.aplayers.length; i++) {
        if (!window.aplayers[i].options.fixed) {
          window.aplayers[i].destroy()
        }
      }
    }
  }

  const runMetingJS = () => {
    typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()
  }

  btf.addGlobalFn('pjaxSend', destroyAplayer, 'destroyAplayer')
  btf.addGlobalFn('pjaxComplete', loadMeting, 'runMetingJS')
})()</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>(() => {
  const pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

  window.pjax = new Pjax({
    elements: 'a:not([target="_blank"])',
    selectors: pjaxSelectors,
    cacheBust: false,
    analytics: false,
    scrollRestoration: false
  })

  const triggerPjaxFn = (val) => {
    if (!val) return
    Object.values(val).forEach(fn => fn())
  }

  document.addEventListener('pjax:send', () => {
    // removeEventListener
    btf.removeGlobalFnEvent('pjaxSendOnce')
    btf.removeGlobalFnEvent('themeChange')

    // reset readmode
    const $bodyClassList = document.body.classList
    if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode')

    triggerPjaxFn(window.globalFn.pjaxSend)
  })

  document.addEventListener('pjax:complete', () => {
    btf.removeGlobalFnEvent('pjaxCompleteOnce')
    document.querySelectorAll('script[data-pjax]').forEach(item => {
      const newScript = document.createElement('script')
      const content = item.text || item.textContent || item.innerHTML || ""
      Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
      newScript.appendChild(document.createTextNode(content))
      item.parentNode.replaceChild(newScript, item)
    })

    triggerPjaxFn(window.globalFn.pjaxComplete)
  })

  document.addEventListener('pjax:error', e => {
    if (e.request.status === 404) {
      const usePjax = true
      true 
        ? (usePjax ? pjax.loadUrl('/404.html') : window.location.href = '/404.html')
        : window.location.href = e.request.responseURL
    }
  })
})()</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="输入你想搜索的关键字" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:24%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163139.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Linux/&quot;);" href="javascript:void(0);">Linux</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163140.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-初阶/&quot;);" href="javascript:void(0);">C++初阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">C语言笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202507101631401.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C语言/&quot;);" href="javascript:void(0);">C语言</a><span class="categoryBar-list-count">22</span><span class="categoryBar-list-descr">Linux笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163130.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Microi吾码/&quot;);" href="javascript:void(0);">Microi吾码</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163135.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-进阶/&quot;);" href="javascript:void(0);">C++进阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">低代码</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163137.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/优选算法/&quot;);" href="javascript:void(0);">优选算法</a><span class="categoryBar-list-count">11</span><span class="categoryBar-list-descr">数据结构笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163136.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端基础/&quot;);" href="javascript:void(0);">前端基础</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">入门常用算法</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163132.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/话题/&quot;);" href="javascript:void(0);">话题</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">前端基础笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163134.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/初阶数据结构/&quot;);" href="javascript:void(0);">初阶数据结构</a><span class="categoryBar-list-count">10</span><span class="categoryBar-list-descr">杂谈</span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题使用Butterfly" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.js"></script><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/77c5921463a44f418828ae47de6671e5.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">DeepSeek、Grok 和 ChatGPT 对比分析：从技术与应用场景的角度深入探讨</a><div class="blog-slider__text">在人工智能领域，随着技术的快速发展，不同的工具和框架不断涌现，为开发者提供了更多选择。DeepSeek、Grok 和 ChatGPT 作为三款备受关注的工具，每一款都有其独特的优势和适用场景。本文将从技术特点、应用场景以及实际案例分析的角度，对这三款工具进行对比，帮助读者更好地理解它们的区别和适用场景</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/44fa280c73e53024f749363207753e1.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">当前就业形势下C++方向后端开发学习指南</a><div class="blog-slider__text">在信息技术飞速发展的今天，后端开发成为了软件开发领域中极其重要的组成部分。对于很多程序员来说，C++仍然是一个强大且广泛应用的编程语言，尤其在后端开发中有着不可忽视的地位。本文将深入探讨C++方向后端开发的学习路线，分析当前就业形势下的职业方向选择，并结合图示和代码示例，帮助读者系统化地学习C++后端开发</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/419f4f95b11526f92f62fe38778d0a9.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">AIGC训练效率与模型优化的深入探讨</a><div class="blog-slider__text">人工智能领域的发展，人工智能生成内容（ [AIGC](https://aigc.izzi.cn/)）越来越受关注。AIGC能够通过学习大量数据生成高质量内容，但训练效率和模型优化仍然是关键的研究方向。本博客将深入探AIGC的训练效率，与模型优化的相关策略和技术，提供相应代码示例和图示，以帮助读者更好地理解该领域</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e640e59c2f92482993b52c845adf7844.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">如何高效利用DeepSeek：深入探索AI搜索引擎的潜力</a><div class="blog-slider__text">随着人工智能技术的飞速发展，传统的搜索引擎正逐步向更智能化、个性化的方向演进。作为一款基于深度学习的AI搜索引擎，DeepSeek（深度求索）不仅在理解用户意图方面展现出色，还通过集成丰富的知识图谱和提供多样化的信息类型，成为现代用户的信息获取利器。本文将详细分析如何高效利用DeepSeek，探讨其核心技术、实际应用场景以及性能优化方法</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2373381f0feae7cd4964af546e9e462.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-01-31</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">如何快速高效本地部署DeepseekR1大模型？保姆级教程 无惧隐私威胁</a><div class="blog-slider__text">DeepSeek 隐私政策中提到了关于用户输入信息收集的条款，无论你输入什么文本，以及上传什么文件都会被第三方机构所收集，所以如果是在进行相关的项目研究或者实验进展分析的时候，就很有必要对数据进行隐私保护，且本地部署是支持离线的</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 280px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/about/'|| '/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.zzh-blog.club/api?ZeroCoder-Zhang",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'ZeroCoder-Zhang')
    }
  </script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","hOffset":40,"vOffset":0,"width":150,"height":300},"mobile":{"show":false},"log":false});</script></body></html>